package com.hl.glidedemo.util

import android.graphics.drawable.Drawable
import android.util.Log
import android.view.View
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition

object GlideUtil {
    private const val TAG = "GlideUtil"

    fun setSrc(
        iv: ImageView,
        imageUrl: String,
        requestOptions: RequestOptions = RequestOptions().centerCrop()
    ) {
        Glide.with(iv).load(imageUrl).apply(requestOptions).into(iv)
    }

    /**
     * 默认是 RequestOptions
     */
    fun setBackground(
        view: View,
        imageUrl: String,
        requestOptions: RequestOptions = RequestOptions().centerCrop(),
    ) {
        Glide.with(view)
            .load(imageUrl)
            .apply(requestOptions)
            .into(object : CustomTarget<Drawable>() {

                override fun onLoadStarted(placeholder: Drawable?) {
                    // 加载开始时可显示占位图
                    // 注意：ImageView作为背景并不支持占位图，此处仅为示例
                }

                override fun onResourceReady(
                    resource: Drawable,
                    transition: Transition<in Drawable>?
                ) {
                    // 加载成功
                    view.background = resource
                }

                override fun onLoadFailed(errorDrawable: Drawable?) {
                    // 加载失败时可处理错误
                    super.onLoadFailed(errorDrawable)
                    view.background = errorDrawable
                }

                override fun onLoadCleared(placeholder: Drawable?) {
                    // // 当资源从内存中清除时可执行清理操作
                    Log.e(TAG, "onLoadCleared: 失败")
                    view.background = placeholder
                }
            })
    }

}